﻿using System.Security.Cryptography;
using System.Text;

namespace HDW_Migrate.Extensions;

/// <summary>
/// RSA加密解密、生成验签和验证验签
/// </summary>
public class RSACryptoService
{
    /// <summary>
    /// 前端加密后端解密，使用的RSA公钥
    /// </summary>
    public const string publicKeyRSA = @"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDHFX4YgS0X6JaPbWMs4UIoFnMc
rAOrpNOKjFYEvHS+Z1xR698de+tZv1YSWeyLNLRvbNbKxIbBpUut5UWb2RoiqRn3
sja5GMUajLMjllK1b9qD/FjL5WmZtS7N+Xq882Gv1RevGYZTQXpvRDODWsDC9zcw
DpHQaiqXEBV/wch/WwIDAQAB";
    /// <summary>
    /// 前端加密后端解密，使用的RSA私钥
    /// </summary>
    public const string privateKeyRSA = @"MIICXAIBAAKBgQDHFX4YgS0X6JaPbWMs4UIoFnMcrAOrpNOKjFYEvHS+Z1xR698d
e+tZv1YSWeyLNLRvbNbKxIbBpUut5UWb2RoiqRn3sja5GMUajLMjllK1b9qD/FjL
5WmZtS7N+Xq882Gv1RevGYZTQXpvRDODWsDC9zcwDpHQaiqXEBV/wch/WwIDAQAB
AoGACcT0Ox+bpuCzArbLdxhWtsDjRTTruTCNcO8SCYl18SIBVcPNXxUFp5HMF3py
MSKU+CLPJ4QdWMNTw2TM1akBrzuU4TwwUkPX8c8zDOYsTJ6aYsk8Lt/8kn3VqOSy
lUHAYZcJdiJOWoVbG7O9LC9V+EGCZ5o3R1bXhjfNOzu0aoECQQDjOuyRH6pkijFn
25rQcjNX0wOVdad0spUK2m46o+cHKwtYeRb+NPqYLxxEUnHs24+DmHG3vde3IXmS
9UOEZsjXAkEA4EpILbPWVSstWfKXUoSVmqfeXMfAINapaLm6n1vGS0l7I9v0JSZL
oTRQi0Ww6UQeemnMnj2PIzSnGDwDfRdZHQJBAJt5EK4HNYXPDBjcqCOhT8Hyjkww
ESCGo/WmGK+kv4knCX9CctoCE8gWy8dvhaWjYKGQp5YpnbQegllr2QN5dEcCQGiP
OIbVx518u2+rQBAf7v5iM69dD5w/dkp0CyQvTIncf6N/7plC+Q71rHbAznBwaST4
HYPHfusSqLMLhzTRpaECQBA3Tn5l33OQVVCByaFCaw6TBtTEx3n76CO0MjQ3CLTN
ISWBhbY3BRJiZffCA2kIWYmouq62K8Izr3F3qUxzPhc=";

    /// <summary>
    /// 后端加密前端解密，使用的RSA公钥
    /// </summary>
    public const string publicKeyRSABackground = @"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDJUJYf0JnCE+zdGXOWYzl+sy10
TenUJYnVnfIQRzsJI9wLuBe1G+agGr3wpcH2hu8I62WuRCaC/kuNkKN3V7PxVo+u
gnIUHSDjfFvdFdBLe0OPcswD/1pHGsXY1GpdMPCFI8GO9F4flZ3+uvDmOvdsjgbp
UTTvfr/G44WaDeu02QIDAQAB";
    /// <summary>
    /// 后端加密前端解密，使用的RSA私钥
    /// </summary>
    public const string privateKeyRSAFront = @"MIICXQIBAAKBgQDJUJYf0JnCE+zdGXOWYzl+sy10TenUJYnVnfIQRzsJI9wLuBe1
G+agGr3wpcH2hu8I62WuRCaC/kuNkKN3V7PxVo+ugnIUHSDjfFvdFdBLe0OPcswD
/1pHGsXY1GpdMPCFI8GO9F4flZ3+uvDmOvdsjgbpUTTvfr/G44WaDeu02QIDAQAB
AoGAE7rhK7cPCrVXNogjCu8omGFJKCfmrdMMAjKbobrJb2jjTQa61BYq8TANw4ML
UnUBAlfHvF+Tgq0XjIVLcAvZZ7YFIAZxzv1xF6nbTleq5qViEu+nUwVQh4PbJXDt
eiKfotbPYHZzJ8YQN24n0sUg5QJl37QVK00gJz7XCdYcYnECQQD6TQdD5BeQvNDH
cABofUUdTgroZaQkHFEWn2xZBdVtfYs801JXq9rY9aDHHHpcyAN0O2ORAh1tmIN+
C/rGT0uFAkEAzeYGPXwxbah2jMlq93zxEntDqifFvqSPIWsf/nHrcPRpmlE657jW
AZIHDMUejDaUSzjYdI4yY5lRi7nsjlkSRQJBAPowrKZsBDIkyfvQNFg9fyw/qh+K
GXwO4e7fBAooDqIW72qpQJFpsqNTQpZEHPtI4kr4Yhm8J3Y5EJaZmt1GvZECQQCr
GDkZQKlmQTX5+am8bIN64xkwPQqSR/Z0Q6t7abjGzSMvy85SHgMfnPPkxayDwRrr
gxpDiKIQp6fenyoWg6etAkA0a6BVqdUfy7aJuru7B+XCUhBN9EZug2JR+leI/3Kn
md9WsAZ//KI72oNuAey+sN36ILOl3TbIc0kH5gkteObb";
    private RSACryptoServiceProvider _privateKeyRsaProvider;
    private RSACryptoServiceProvider _publicKeyRsaProvider;

    /// <summary>
    public RSACryptoService(string privateKey, string publicKey = null)
    {
        if (!string.IsNullOrEmpty(privateKey))
        {
            _privateKeyRsaProvider = CreateRsaProviderFromPrivateKey(privateKey);
        }

        if (!string.IsNullOrEmpty(publicKey))
        {
            _publicKeyRsaProvider = CreateRsaProviderFromPublicKey(publicKey);
        }
    }
    /// <summary>
    /// RSA解密，密文为空，将原值返回。本方法自带解密分组加密的密文，能解密出超过117个字符明文。
    /// 对应的前端网页的JavaScript方法，加密最多117个纯中文字符也不报错，但是当前的这个后端解密方法无法解密，如果最多加密39个纯中文字符，则当前的这个后端解密方法能够解密。
    /// </summary>
    /// <param name="cipherText">密文为空，将原值返回</param>
    /// <returns></returns>
    public string Decrypt(string cipherText)
    {
        if (_privateKeyRsaProvider == null)
        {
            throw new Exception("_privateKeyRsaProvider is null");
        }
        if (string.IsNullOrEmpty(cipherText))
        {
            return cipherText;
        }
        return Decrypt2(cipherText);
        //return Encoding.UTF8.GetString(_privateKeyRsaProvider.Decrypt(System.Convert.FromBase64String(cipherText), false));
    }
    /// <summary>
    /// RSA加密，明文为空，将原值返回。本方法自带分组加密功能，能加密超过117个字符。
    /// </summary>
    /// <param name="text"></param>
    /// <returns></returns>
    public string Encrypt(string text)
    {
        if (_publicKeyRsaProvider == null)
        {
            throw new Exception("_publicKeyRsaProvider is null");
        }
        if (string.IsNullOrEmpty(text))
        {
            return text;
        }
        return Encrypt2(text);
        //return Convert.ToBase64String(_publicKeyRsaProvider.Encrypt(Encoding.UTF8.GetBytes(text), false));

    }

    /// <summary>
    /// 签名数据
    /// </summary>
    /// <param name="data">数据源值</param>
    /// <param name="charset">字符编码</param>
    /// <param name="signType">签名类型SHA1  SHA256</param>
    /// <returns></returns>
    public string SignData(string data, string charset = "utf-8", string signType = "SHA1")
    {
        byte[] dataBytes = null;
        if (string.IsNullOrEmpty(charset))
        {
            dataBytes = Encoding.UTF8.GetBytes(data);
        }
        else
        {
            dataBytes = Encoding.GetEncoding(charset).GetBytes(data);
        }

        byte[] signatureBytes = _privateKeyRsaProvider.SignData(dataBytes, signType);

        return Convert.ToBase64String(signatureBytes);
    }

    /// <summary>
    public bool VerifyData(string signContent, string sign, string charset = "utf-8", string signType = "SHA1")
    {
        try
        {
            switch (signType)
            {
                case "SHA1":
                    SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
                    bool bVerifyResultOriginal = _publicKeyRsaProvider.VerifyData(Encoding.GetEncoding(charset).GetBytes(signContent), sha1, Convert.FromBase64String(sign));
                    return bVerifyResultOriginal;
                case "SHA256":
                    SHA256CryptoServiceProvider sha256 = new SHA256CryptoServiceProvider();
                    return _publicKeyRsaProvider.VerifyData(Encoding.GetEncoding(charset).GetBytes(signContent), sha256, Convert.FromBase64String(sign));
                default:
                    return false;
                    //break;
            }

        }
        catch
        {
            return false;
        }
    }


    private RSACryptoServiceProvider CreateRsaProviderFromPrivateKey(string privateKey)
    {
        var privateKeyBits = System.Convert.FromBase64String(privateKey);

        var RSA = new RSACryptoServiceProvider();
        var RSAparams = new RSAParameters();

        using (BinaryReader binr = new BinaryReader(new MemoryStream(privateKeyBits)))
        {
            byte bt = 0;
            ushort twobytes = 0;
            twobytes = binr.ReadUInt16();
            if (twobytes == 0x8130)
                binr.ReadByte();
            else if (twobytes == 0x8230)
                binr.ReadInt16();
            else
                throw new Exception("Unexpected value read binr.ReadUInt16()");

            twobytes = binr.ReadUInt16();
            if (twobytes != 0x0102)
                throw new Exception("Unexpected version");

            bt = binr.ReadByte();
            if (bt != 0x00)
                throw new Exception("Unexpected value read binr.ReadByte()");

            RSAparams.Modulus = binr.ReadBytes(GetIntegerSize(binr));
            RSAparams.Exponent = binr.ReadBytes(GetIntegerSize(binr));
            RSAparams.D = binr.ReadBytes(GetIntegerSize(binr));
            RSAparams.P = binr.ReadBytes(GetIntegerSize(binr));
            RSAparams.Q = binr.ReadBytes(GetIntegerSize(binr));
            RSAparams.DP = binr.ReadBytes(GetIntegerSize(binr));
            RSAparams.DQ = binr.ReadBytes(GetIntegerSize(binr));
            RSAparams.InverseQ = binr.ReadBytes(GetIntegerSize(binr));
        }

        RSA.ImportParameters(RSAparams);
        return RSA;
    }

    private int GetIntegerSize(BinaryReader binr)
    {
        byte bt = 0;
        byte lowbyte = 0x00;
        byte highbyte = 0x00;
        int count = 0;
        bt = binr.ReadByte();
        if (bt != 0x02)
            return 0;
        bt = binr.ReadByte();

        if (bt == 0x81)
            count = binr.ReadByte();
        else
            if (bt == 0x82)
        {
            highbyte = binr.ReadByte();
            lowbyte = binr.ReadByte();
            byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };
            count = BitConverter.ToInt32(modint, 0);
        }
        else
        {
            count = bt;
        }

        while (binr.ReadByte() == 0x00)
        {
            count -= 1;
        }
        binr.BaseStream.Seek(-1, SeekOrigin.Current);
        return count;
    }

    private RSACryptoServiceProvider CreateRsaProviderFromPublicKey(string publicKeyString)
    {
        // encoded OID sequence for  PKCS #1 rsaEncryption szOID_RSA_RSA = "1.2.840.113549.1.1.1"
        byte[] SeqOID = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 };
        byte[] x509key;
        byte[] seq = new byte[15];
        int x509size;

        x509key = Convert.FromBase64String(publicKeyString);
        x509size = x509key.Length;

        // ---------  Set up stream to read the asn.1 encoded SubjectPublicKeyInfo blob  ------
        using (MemoryStream mem = new MemoryStream(x509key))
        {
            using (BinaryReader binr = new BinaryReader(mem))  //wrap Memory Stream with BinaryReader for easy reading
            {
                byte bt = 0;
                ushort twobytes = 0;

                twobytes = binr.ReadUInt16();
                if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
                    binr.ReadByte();    //advance 1 byte
                else if (twobytes == 0x8230)
                    binr.ReadInt16();   //advance 2 bytes
                else
                    return null;

                seq = binr.ReadBytes(15);       //read the Sequence OID
                if (!CompareBytearrays(seq, SeqOID))    //make sure Sequence for OID is correct
                    return null;

                twobytes = binr.ReadUInt16();
                if (twobytes == 0x8103) //data read as little endian order (actual data order for Bit String is 03 81)
                    binr.ReadByte();    //advance 1 byte
                else if (twobytes == 0x8203)
                    binr.ReadInt16();   //advance 2 bytes
                else
                    return null;

                bt = binr.ReadByte();
                if (bt != 0x00)     //expect null byte next
                    return null;

                twobytes = binr.ReadUInt16();
                if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
                    binr.ReadByte();    //advance 1 byte
                else if (twobytes == 0x8230)
                    binr.ReadInt16();   //advance 2 bytes
                else
                    return null;

                twobytes = binr.ReadUInt16();
                byte lowbyte = 0x00;
                byte highbyte = 0x00;

                if (twobytes == 0x8102) //data read as little endian order (actual data order for Integer is 02 81)
                    lowbyte = binr.ReadByte();  // read next bytes which is bytes in modulus
                else if (twobytes == 0x8202)
                {
                    highbyte = binr.ReadByte(); //advance 2 bytes
                    lowbyte = binr.ReadByte();
                }
                else
                    return null;
                byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };   //reverse byte order since asn.1 key uses big endian order
                int modsize = BitConverter.ToInt32(modint, 0);

                int firstbyte = binr.PeekChar();
                if (firstbyte == 0x00)
                {   //if first byte (highest order) of modulus is zero, don't include it
                    binr.ReadByte();    //skip this null byte
                    modsize -= 1;   //reduce modulus buffer size by 1
                }

                byte[] modulus = binr.ReadBytes(modsize);   //read the modulus bytes

                if (binr.ReadByte() != 0x02)            //expect an Integer for the exponent data
                    return null;
                int expbytes = (int)binr.ReadByte();        // should only need one byte for actual exponent data (for all useful values)
                byte[] exponent = binr.ReadBytes(expbytes);

                // ------- create RSACryptoServiceProvider instance and initialize with public key -----
                RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
                RSAParameters RSAKeyInfo = new RSAParameters();
                RSAKeyInfo.Modulus = modulus;
                RSAKeyInfo.Exponent = exponent;
                RSA.ImportParameters(RSAKeyInfo);

                return RSA;
            }

        }
    }

    private bool CompareBytearrays(byte[] a, byte[] b)
    {
        if (a.Length != b.Length)
            return false;
        int i = 0;
        foreach (byte c in a)
        {
            if (c != b[i])
                return false;
            i++;
        }
        return true;
    }


    private string Encrypt2(string text)
    {


        Byte[] PlaintextData = Encoding.UTF8.GetBytes(text);
        int MaxBlockSize = _publicKeyRsaProvider.KeySize / 8 - 11;    //加密块最大长度限制

        if (PlaintextData.Length <= MaxBlockSize)
        {
            return Convert.ToBase64String(_publicKeyRsaProvider.Encrypt(PlaintextData, false));
        }
        else
        {
            using (MemoryStream PlaiStream = new MemoryStream(PlaintextData))
            using (MemoryStream CrypStream = new MemoryStream())
            {
                Byte[] Buffer = new Byte[MaxBlockSize];
                int BlockSize = PlaiStream.Read(Buffer, 0, MaxBlockSize);

                while (BlockSize > 0)
                {
                    Byte[] ToEncrypt = new Byte[BlockSize];
                    Array.Copy(Buffer, 0, ToEncrypt, 0, BlockSize);

                    Byte[] Cryptograph = _publicKeyRsaProvider.Encrypt(ToEncrypt, false);
                    CrypStream.Write(Cryptograph, 0, Cryptograph.Length);

                    BlockSize = PlaiStream.Read(Buffer, 0, MaxBlockSize);
                }

                return Convert.ToBase64String(CrypStream.ToArray(), Base64FormattingOptions.None);
            }
        }




    }

    private string Decrypt2(string ciphertext)
    {


        Byte[] CiphertextData = Convert.FromBase64String(ciphertext);
        int MaxBlockSize = _privateKeyRsaProvider.KeySize / 8;    //解密块最大长度限制

        if (CiphertextData.Length <= MaxBlockSize)
            return System.Text.Encoding.UTF8.GetString(_privateKeyRsaProvider.Decrypt(CiphertextData, false));

        using (MemoryStream CrypStream = new MemoryStream(CiphertextData))
        using (MemoryStream PlaiStream = new MemoryStream())
        {
            Byte[] Buffer = new Byte[MaxBlockSize];
            int BlockSize = CrypStream.Read(Buffer, 0, MaxBlockSize);

            while (BlockSize > 0)
            {
                Byte[] ToDecrypt = new Byte[BlockSize];
                Array.Copy(Buffer, 0, ToDecrypt, 0, BlockSize);

                Byte[] Plaintext = _privateKeyRsaProvider.Decrypt(ToDecrypt, false);
                PlaiStream.Write(Plaintext, 0, Plaintext.Length);

                BlockSize = CrypStream.Read(Buffer, 0, MaxBlockSize);
            }

            return System.Text.Encoding.UTF8.GetString(PlaiStream.ToArray());
        }
    }

    #region 获取Hash描述表 
    //获取Hash描述表 
    public bool GetHash(string m_strSource, ref byte[] HashData, string charset = "utf-8")
    {
        //从字符串中取得Hash描述 
        byte[] Buffer;
        System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5");
        Buffer = System.Text.Encoding.GetEncoding(charset).GetBytes(m_strSource);//GB2312
        HashData = MD5.ComputeHash(Buffer);

        return true;
    }

    //获取Hash描述表 
    public bool GetHash(string m_strSource, ref string strHashData, string charset = "utf-8")
    {

        //从字符串中取得Hash描述 
        byte[] Buffer;
        byte[] HashData;
        System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5");
        Buffer = System.Text.Encoding.GetEncoding(charset).GetBytes(m_strSource);//GB2312
        HashData = MD5.ComputeHash(Buffer);

        strHashData = Convert.ToBase64String(HashData);
        return true;

    }

    //获取Hash描述表 
    public bool GetHash(System.IO.FileStream objFile, ref byte[] HashData)
    {

        //从文件中取得Hash描述 
        System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5");
        HashData = MD5.ComputeHash(objFile);
        objFile.Close();

        return true;

    }

    //获取Hash描述表 
    public bool GetHash(System.IO.FileStream objFile, ref string strHashData)
    {

        //从文件中取得Hash描述 
        byte[] HashData;
        System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5");
        HashData = MD5.ComputeHash(objFile);
        objFile.Close();

        strHashData = Convert.ToBase64String(HashData);

        return true;

    }
    #endregion

    /// <summary>
    /// MD5withRas生成签名，先做MD5签名，再做私钥加密
    /// </summary>
    /// <param name="p_strKeyPrivate">私钥</param>
    /// <param name="m_strHashbyteSignature">经过Hash的明文</param>
    /// <param name="m_strEncryptedSignatureData">输出最终验签</param>
    /// <returns></returns>
    public bool SignatureFormatter(string p_strKeyPrivate, string m_strHashbyteSignature, ref string m_strEncryptedSignatureData)
    {
        byte[] HashbyteSignature;
        byte[] EncryptedSignatureData;
        HashbyteSignature = Convert.FromBase64String(m_strHashbyteSignature);
        System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
        RSA = CreateRsaProviderFromPrivateKey(p_strKeyPrivate);
        /* 测试RSA的私钥XML格式能否与字符串格式自由等效转换  
        string xml = RSA.ToXmlString(true);
        Console.WriteLine("privateXml:" + xml);
        System.Security.Cryptography.RSACryptoServiceProvider RSA1 = new System.Security.Cryptography.RSACryptoServiceProvider();
        RSA1.FromXmlString(xml);
        Console.WriteLine("privateRight:" + (RSA1.ToXmlString(true) == xml));
        */
        System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA);
        //设置签名的算法为MD5 
        RSAFormatter.SetHashAlgorithm("MD5");
        //执行签名 
        EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature);
        m_strEncryptedSignatureData = Convert.ToBase64String(EncryptedSignatureData);
        return true;
    }

    /// <summary>
    /// MD5withRas验证验签
    /// </summary>
    /// <param name="p_strKeyPublic">公钥</param>
    /// <param name="p_strHashbyteDeformatter">经过Hash的明文</param>
    /// <param name="p_strDeformatterData">传入最终验签</param>
    /// <returns></returns>
    public bool SignatureDeformatter(string p_strKeyPublic, string p_strHashbyteDeformatter, string p_strDeformatterData)
    {
        byte[] DeformatterData;
        byte[] HashbyteDeformatter;
        HashbyteDeformatter = Convert.FromBase64String(p_strHashbyteDeformatter);
        System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
        RSA = CreateRsaProviderFromPublicKey(p_strKeyPublic);
        /* 测试RSA的公钥XML格式能否与字符串格式自由等效转换          
        string xml = RSA.ToXmlString(false);
        Console.WriteLine("publicXml:" + xml);
        System.Security.Cryptography.RSACryptoServiceProvider RSA1 = new System.Security.Cryptography.RSACryptoServiceProvider();
        RSA1.FromXmlString(xml);
        Console.WriteLine("publicRight:" + (RSA1.ToXmlString(false)== xml));
        */
        System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA);
        //指定解密的时候HASH算法为MD5 
        RSADeformatter.SetHashAlgorithm("MD5");
        DeformatterData = Convert.FromBase64String(p_strDeformatterData);
        if (RSADeformatter.VerifySignature(HashbyteDeformatter, DeformatterData))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

}
